package cn.shujuhai.cms.controller.article;

import cn.hutool.core.util.StrUtil;
import cn.shujuhai.common.pluging.data.ResultVo;
import cn.shujuhai.common.pluging.file.FilesUtils;
import cn.shujuhai.common.service.SettingService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("cms/ueditor")
@RequiredArgsConstructor
public class UEditorController {

    @Value("${template.static.imageUrl}")
    public String UPLOAD_IMAGE_DIR; //文章视频路径

    @Value("${template.static.viewImageUrl}")
    public String VIEW_IMAGE_DIR;        //文章视频访问路径

    @Value("${template.static.videoUrl}")
    public String UPLOAD_VIDEO_DIR; //文章视频路径

    @Value("${template.static.viewVideoUrl}")
    public String VIEW_VIDEO_DIR;        //文章视频访问路径

    @Value("${server.servlet.context-path}")
    public String BASE_URL;

    final CacheManager cacheManager;


    // 处理所有 ueditor 请求
    @RequestMapping("/upload")
    public void ueditorUpload(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(value = "upfile", required = false) MultipartFile file) throws IOException {

        String action = request.getParameter("action");

        // 设置响应类型
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        Cache cache = cacheManager.getCache("sys_setting");
        if (cache == null) {
            throw new IllegalStateException("未获取到缓存");
        }
        String imageSize = cache.get("EDITOR_IMAGE", String.class);
        imageSize = StrUtil.trim(imageSize);
        int imageMaxSize = StrUtil.isNotEmpty(imageSize) ? Integer.parseInt(imageSize) : 2048;
        String videoSize = cache.get("EDITOR_VIDOE", String.class);
        videoSize = StrUtil.trim(videoSize);
        int videoMaxSize = StrUtil.isNotEmpty(videoSize) ? Integer.parseInt(videoSize) : 102400;
        if ("config".equals(action)) {
            Map<String, Object> config = new HashMap<>();

            config.put("imageActionName", "uploadimage");
            config.put("imageFieldName", "upfile");
            config.put("imageMaxSize", imageMaxSize * 1024);
            config.put("imageAllowFiles", new String[]{".png", ".jpg", ".jpeg", ".gif", ".bmp"});
            config.put("imageUrlPrefix", BASE_URL); // 动态路径

            config.put("videoActionName", "uploadvideo");
            config.put("videoFieldName", "upfile");
            config.put("videoMaxSize", videoMaxSize * 1024);
            config.put("videoAllowFiles", new String[]{".mp4", ".avi", ".wmv", ".flv"});
            config.put("videoUrlPrefix", BASE_URL); // 动态路径

            response.getWriter().write(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(config));
            return;
        }


        // 处理图片、视频上传
        if ("uploadimage".equals(action) || "uploadvideo".equals(action)) {
            String savePath;
            String urlPrefix;
            if ("uploadimage".equals(action)) {
                savePath = UPLOAD_IMAGE_DIR;
                urlPrefix = VIEW_IMAGE_DIR;
            } else {
                savePath = UPLOAD_VIDEO_DIR;
                urlPrefix = VIEW_VIDEO_DIR;
            }

            // 保存文件
            String originalName = file.getOriginalFilename();
            String uploadFile = FilesUtils.uploadFile(file, savePath, urlPrefix);
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("state", "SUCCESS");
            result.put("url", uploadFile);
            result.put("title", originalName);
            result.put("original", originalName);

            response.getWriter().write(new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(result));
        }
    }
}
